package com.jike.mahjong.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jike.mahjong.model.Player;
import com.jike.mahjong.service.PlayerService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.jike.mahjong.common.Constants;
import com.jike.mahjong.common.Page;
import com.jike.mahjong.common.util.GsonUtil;
import com.jike.mahjong.common.util.HttpUtil;
import com.jike.mahjong.common.util.MD5Util;
import com.jike.mahjong.model.Club;
import com.jike.mahjong.model.CoinRecordModel;
import com.jike.mahjong.model.Manager;
import com.jike.mahjong.model.TradeRecord;
import com.jike.mahjong.service.PersonService;


/**
 * Created by star on 2016/9/29.
 */
@Controller
public class UserContoller {

    private Logger log = Logger.getLogger(UserContoller.class);

    @Autowired
    private PersonService personService;

    @Autowired
    private PlayerService playerService;
   /* @Autowired
    private TradeService tradeService;
*/
    /**
     * 程序入口
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/user/login.html", method = {RequestMethod.GET,
            RequestMethod.POST})
    protected ModelAndView login(HttpServletRequest request, HttpServletResponse response, Manager user) throws Exception {

        if (request.getParameter("userAccount") == null) {
            return theEnter(request, response);
        }
        return userLogin(request, response, user);
    }

    /**
     * 代理程序入口
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/agent/login.html", method = {RequestMethod.GET,
            RequestMethod.POST})
    protected ModelAndView agentLogin(HttpServletRequest request, HttpServletResponse response, Manager user) throws Exception {

        if (request.getParameter("userAccount") == null) {
            return theEnter1(request, response);
        }
        return userLogin1(request, response, user);
    }

    public ModelAndView theEnter(HttpServletRequest request, HttpServletResponse response) {
        // 清除错误消息
        HttpUtil.setSessionAttribute(request, "message", "");
        return new ModelAndView("views/login");
    }
    
    public ModelAndView theEnter1(HttpServletRequest request, HttpServletResponse response) {
        // 清除错误消息
        HttpUtil.setSessionAttribute(request, "message", "");
        return new ModelAndView("views/agentlogin");
    }

    public ModelAndView userLogin(HttpServletRequest request, HttpServletResponse response, Manager model) {
        Manager user = null;
        String message = "";

        Map<String, Object> paraMap = new HashMap<String, Object>();

        try {
            String userAccount = model.getUserAccount();
            // String userName = model.getUserName();
            String password = model.getPassword();
            paraMap.put("userAccount", userAccount);
            paraMap.put("userType",Constants.MANAGER_TYPE_ROOT);

            List<Manager> userList= personService.getManagerByRole(paraMap);
            if (userList != null&&userList.size()>0) {
                user = personService.getManagerByRole(paraMap).get(0);
                if (user.getPassword().equals(MD5Util.GetMD5Code(password))) {
                    log.info("##登陆用户名密码验证成功，当前登陆用户：" + user.getUserName()+"\n 登录地址:"+request.getLocalAddr());
                    HttpUtil.setSessionAttribute(request, "loginUser", user);
                    HttpUtil.setSessionAttribute(request, "loginUserName", user.getUserName());
                    HttpUtil.setSessionAttribute(request, "m_user_id", user.getId());
                } else {
                    log.info("##密码错误##");
                    message = "密码错误，请输入正确密码！";
                    HttpUtil.setSessionAttribute(request, "message", message);
                    HttpUtil.setSessionAttribute(request, "errorcode", user.getUserAccount());
                    return new ModelAndView("views/login");
                }
            } else {
                log.info("##无此用户##");
                message = "无此用户，请输入正确的登录名称！";
                HttpUtil.setSessionAttribute(request, "message", message);
                return new ModelAndView("views/login");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("##登陆报错：" + e.getMessage() + "##");
            return new ModelAndView("views/login");
        }

        log.info("##登陆成功##"+"\n 登录地址:"+request.getLocalAddr());
//        后续操作
        Map<String, Object> mapm = new HashMap<String, Object>();
        mapm.put("loginName", HttpUtil.getSessionAttribute(request, "loginUserName"));
        mapm.put("loginUser", HttpUtil.getSessionAttribute(request, "loginUser"));
        if(user.getUserType()==0){
        return new 	ModelAndView("views/manager/agentmanager", mapm);
        }
        return new ModelAndView("views/index", mapm);
    }
    public ModelAndView userLogin1(HttpServletRequest request, HttpServletResponse response, Manager model) {
        Manager user = null;
        String message = "";
        log.info("##无此用户##");
        message = "无此用户，请输入正确的登录名称！";
        HttpUtil.setSessionAttribute(request, "message", message);
        return new ModelAndView("views/agentlogin");
//        Map<String, Object> paraMap = new HashMap<String, Object>();
//
//        try {
//            String userAccount = model.getUserAccount();
//           // String userName = model.getUserName();
//            String password = model.getPassword();
//            paraMap.put("userAccount", userAccount);
//            paraMap.put("userType",Constants.MANAGER_TYPE_SUBAGENT);
//             List<Manager> userList= personService.getManagerByConditon(paraMap);
//            if (userList != null&&userList.size()>0) {
//                user=personService.getManagerByConditon(paraMap).get(0);
//                if (user.getPassword().equals(MD5Util.GetMD5Code(password))) {
//                    log.info("##登陆用户名密码验证成功，当前登陆用户：" + user.getUserName());
//                    HttpUtil.setSessionAttribute(request, "loginUser", user);
//                    HttpUtil.setSessionAttribute(request, "loginUserName", user.getUserName());
//                    HttpUtil.setSessionAttribute(request, "s_user_id", user.getId());
//                } else {
//                    log.info("##密码错误##");
//                    message = "密码错误，请输入正确密码！";
//                    HttpUtil.setSessionAttribute(request, "message", message);
//                    HttpUtil.setSessionAttribute(request, "errorcode", user.getUserAccount());
//                    return new ModelAndView("views/agentlogin");
//                }
//            } else {
//                log.info("##无此用户##");
//                message = "无此用户，请输入正确的登录名称！";
//                HttpUtil.setSessionAttribute(request, "message", message);
//                return new ModelAndView("views/agentlogin");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("##登陆报错：" + e.getMessage() + "##");
//            return new ModelAndView("views/agentlogin");
//        }
//
//        log.info("##登陆成功##");
////        后续操作
//        Map<String, Object> mapm = new HashMap<String, Object>();
//        mapm.put("loginName", HttpUtil.getSessionAttribute(request, "loginUserName"));
//        mapm.put("loginUser", HttpUtil.getSessionAttribute(request, "loginUser"));
//        return new 	ModelAndView("views/manager/agentmanager", mapm);
    }

    /**
     * 退出程序
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/user/logout", method = {RequestMethod.GET, RequestMethod.POST})
    public String logOut(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 清空session
            HttpSession session = request.getSession(false);
            if (session != null || session.getAttribute("loginUserName") != null) {
                request.getSession().removeAttribute("loginUser");
                request.getSession().invalidate();
            }
        } catch (Exception e) {
            log.error("【error】退出报错：" + e);
        }

        return "views/login";
    }
    /**
     * 代理退出
     */
    @RequestMapping(value = "/agent/logout", method = {RequestMethod.GET, RequestMethod.POST})
    public String agentLogOut(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 清空session
            HttpSession session = request.getSession(false);
            if (session != null || session.getAttribute("loginUserName") != null) {
                request.getSession().removeAttribute("loginUser");
                request.getSession().invalidate();
            }
        } catch (Exception e) {
            log.error("【error】退出报错：" + e);
        }

        return "views/agentlogin";
    }
    
    /**
     * 修改密码
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/manager/changePwd.html", method = {RequestMethod.GET,
            RequestMethod.POST})
    @ResponseBody
    protected Object changePwd(HttpServletRequest request, HttpServletResponse response,Model model) throws Exception {

        String userId = HttpUtil.getHttpParameter(request, "user_id");
        String newPwd = HttpUtil.getHttpParameter(request, "newPwd");

        Map<String, Object> mapm = new HashMap<String, Object>();
        mapm.put("id", userId);
        mapm.put("password", MD5Util.GetMD5Code(newPwd));
        int effectRow = personService.changePwd(mapm);
        mapm.put("effectRow",effectRow);
        return mapm;
    }


    /**
     * 修改密码
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/manager/resetPwd.html", method = {RequestMethod.GET,
            RequestMethod.POST})
    @ResponseBody
    protected Object resetPwd(HttpServletRequest request, HttpServletResponse response,Model model) throws Exception {

        String userId = HttpUtil.getHttpParameter(request, "user_id");

        Map<String, Object> mapm = new HashMap<String, Object>();
        mapm.put("id", userId);
        mapm.put("password", MD5Util.GetMD5Code(Constants.DEFAULT_PWD));
        int effectRow = personService.changePwd(mapm);
        mapm.put("effectRow",effectRow);
        return mapm;
    }


    /**
     * 删除管理员
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/manager/deleteManager.html", method = {RequestMethod.GET,
            RequestMethod.POST})
    @ResponseBody
    protected Object deleteManager(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String userId = HttpUtil.getHttpParameter(request, "user_id");

        Map<String, Object> mapm = new HashMap<String, Object>();
        mapm.put("id", userId);
        mapm.put("delTag",Constants.PLAYER_DELETE);
        int effectRow = personService.deleteManager(mapm);
        mapm.put("effectRow",effectRow);
        return mapm;
    }



    /**
     * 获取所有管理员列表
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/manager/getManagerList.html", method = {RequestMethod.GET,
            RequestMethod.POST})
    protected String getAllManagerList(HttpServletRequest request, HttpServletResponse response, Manager user, Model model) throws Exception {

        List<Manager> managerList = new ArrayList<Manager>();
        managerList = personService.getAllManager();
        model.addAttribute("managerList", managerList);
        return "views/manager/managerInfo";
    }



    @RequestMapping(value = "/manager/getManagers.html", method = {RequestMethod.GET,
            RequestMethod.POST})
    protected String getAllManagerByCondition(HttpServletRequest request, HttpServletResponse response, Manager user, Model model) throws Exception {
        List<Manager> managerList = new ArrayList<Manager>();
        Map<String, Object> mapm = new HashMap<String, Object>();

        String userName =HttpUtil.getHttpParameter(request, "userName");
        if(userName!=null&&!"".equals(userName)){
            mapm.put("userName", userName.trim());
            model.addAttribute("userName",userName.trim());
        }


        managerList = personService.getManagerByConditon(mapm);
        model.addAttribute("userName",userName);
        model.addAttribute("managerList", managerList);
        return "views/manager/managerInfo2";
    }


    @RequestMapping(value = "/manager/addManager.html", method = {RequestMethod.GET,
            RequestMethod.POST})
    protected String addManagerInfo(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        Map<String, Object> para = new HashMap<String, Object>();

        Manager manager = new Manager();
        manager.setUserAccount(HttpUtil.getHttpParameter(request, "manager_account"));
        manager.setUserName(HttpUtil.getHttpParameter(request, "manager_name"));

        manager.setManagerType(Integer.valueOf(HttpUtil.getHttpParameter(request, "manager_type")));
        int effectRow =personService.addManager(manager);

        List<Manager> managerList = personService.getAllManager();
        model.addAttribute("managerList", managerList);
        return "views/manager/managerInfo";
    }

    

/*    @RequestMapping(value = "/manager/agentSellCoin.html", method = {RequestMethod.GET,
            RequestMethod.POST})
    protected String agentSellCoin(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
//        Map<String, Object> para = new HashMap<String, Object>();

        Manager manager = new Manager();
        manager.setUserAccount(HttpUtil.getHttpParameter(request, "manager_account"));
        manager.setUserName(HttpUtil.getHttpParameter(request, "manager_name"));

        manager.setManagerType(Integer.valueOf(HttpUtil.getHttpParameter(request, "manager_type")));
        int effectRow =personService.addManager(manager);

        List<Manager> managerList = personService.getAllManager();
        model.addAttribute("managerList", managerList);
        return "views/manager/managerInfo";
    }
    */

    /**
	 * 代理出售钻石
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "/manager/agentSellCoin.html", method = RequestMethod.POST)
	@ResponseBody
	public Object modifyRefundStatus(@RequestBody Map<String, Object> params,HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> mapResult = new HashMap<String,Object>();
		if(StringUtils.isEmpty(params.get("playerId").toString())||StringUtils.isEmpty(params.get("coin").toString())){
			mapResult.put("errorCode", "10001");
        	mapResult.put("errorMsg", "玩家Id和出售钻石不能为空");
			return mapResult;
		}
		String managerId = request.getSession().getAttribute("s_user_id").toString();

        String userId=params.get("playerId").toString();
        CoinRecordModel coinRecordModel = new CoinRecordModel();
        coinRecordModel.setMahjongCoin(Integer.parseInt(params.get("coin").toString()));
        coinRecordModel.setManagerId(managerId);
        coinRecordModel.setPlayerId(userId);
        coinRecordModel.setAmount(Integer.parseInt(params.get("amount").toString()));
        try {
        	mapResult = personService.insertAgentSellCoin(coinRecordModel);
        	log.info("出售钻石--地址:"+request.getLocalAddr());
		} catch (Exception e) {
            mapResult.put("errorCode", "1");
            mapResult.put("errorMsg", "出售失败");
		}
		return mapResult;

	}


	/**
	 * 代理查询出售钻石历史记录
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "/manager/agentQuerySellHistory.html", method = RequestMethod.POST)
	@ResponseBody
	public Object agentQuerySellHistory(@RequestBody Map<String, Object> params,HttpServletRequest request, HttpServletResponse response) {

        Page page=new Page();

        String currentPage = (String) params.get("pageIndex");

        if(!"".equals(currentPage)&&currentPage!=null){
            page.setCurrentPage(Integer.parseInt(currentPage));

        }else{
            page.setCurrentPage(1);
        }

        Map<String, Object> mapResult = new HashMap<String,Object>();
		String managerId = request.getSession().getAttribute("s_user_id").toString();

		Map<String, Object> map = new HashMap<String,Object>();
        map.put("userId", managerId);
        map.put("playerRole", Constants.PLAYER_ROLE);
        page=playerService.queryPlayerRechargeRecord(map,page);
//        List<CoinRecordModel> list = personService.querySellHistory(map,page);
        mapResult.put("errorCode", "0");
        mapResult.put("page", page);
		return mapResult;

	}


	/**
	 * 获取当前代理用户信息
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "/manager/agentQueryCurrentInfo.html", method = RequestMethod.POST)
	@ResponseBody
	public Object agentQueryCurrentInfo(@RequestBody Map<String, Object> params,HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> mapResult = new HashMap<String,Object>();
		String managerId = request.getSession().getAttribute("s_user_id").toString();

		Map<String, Object> map = new HashMap<String,Object>();
        map.put("userId", managerId);
        map.put("userType", "0");
        Manager manager = personService.queryManagerInfo(map);
        mapResult.put("errorCode", "0");
        mapResult.put("managerInfo", manager);
		return mapResult;
	}

	  /**
     * 代理财富值查询入口
     *
     * @param request
     * @param response
     * @param player
     * @param model
     * @return
     */
    @RequestMapping(value = "/agent/agentCoinOperate.html", method = {RequestMethod.GET, RequestMethod.POST})
    public String agentCoinOperate(HttpServletRequest request, HttpServletResponse response,Manager manager, Model model) {

        Map<String, Object> para = new HashMap<String, Object>();
        if (manager != null) {
            para.put("userId",manager.getId());
            model.addAttribute("userId",manager.getId());
        }
        Page page=new Page();
        String currentPage = HttpUtil.getHttpParameter(request, "pageIndex");

        if(!"".equals(currentPage)&&currentPage!=null){
            page.setCurrentPage(Integer.parseInt(currentPage));

        }else{
            page.setCurrentPage(1);
        }
        page=personService.queryAgentList(para,page);
        model.addAttribute("page", page);
        return "views/player/agentotherInfo";
    }


    /**
     * 加钻
     * @param request
     * @param response
     * @param coin
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/agent/agentCoinAdd.html", method = {RequestMethod.GET, RequestMethod.POST})
    public Map<String, Object> agentCoinAdd(HttpServletRequest request, HttpServletResponse response, TradeRecord trade, Model model) {
        Map<String, Object> paraMap = new HashMap<String, Object>();
        String managerId = request.getSession().getAttribute("m_user_id").toString();
        int effectRow = 0;
        if (trade != null) {
            try {

                Manager manager = (Manager) request.getSession().getAttribute("loginUser");
                trade.setManagerId(managerId);
                trade.setOrderId(getRandomNum());
                effectRow = personService.addAgentCoin(trade);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        if(effectRow>1){
            Player player=playerService.queryPlayInfoById(paraMap);
            paraMap.put("nowCoin",player.getDiamond());
            log.info("agentCoinAdd出售钻石:"+trade.getTradeCoin()+"\n 地址:"+request.getLocalAddr());
        }
        paraMap.put("coinModel", trade);
            paraMap.put("effectRow", effectRow);
        return paraMap;
    }

    @RequestMapping(value = "/agent/getTradeSellHistory.html", method = {RequestMethod.GET, RequestMethod.POST})
    public String getTradeSellHistory(HttpServletRequest request, HttpServletResponse response, CoinRecordModel coin, Model model) {
        Map<String, Object> para = new HashMap<String, Object>();
        Page page=new Page();
        String userId=HttpUtil.getHttpParameter(request,"userId");
        String currentPage = HttpUtil.getHttpParameter(request, "pageIndex");

        para.put("userId",userId);


        if(!"".equals(currentPage)&&currentPage!=null){
            page.setCurrentPage(Integer.parseInt(currentPage));

        }else{
            page.setCurrentPage(1);
        }
//        page=tradeService.queryTradeRecordHistoryByManager(para, page);

        model.addAttribute("page",page);
        model.addAttribute("userId",userId);
        return "views/player/agentRechargeRecord";
    }

    /**
     * 修改密码
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/agent/changePwd.html", method = {RequestMethod.GET, RequestMethod.POST})
    protected Object agentChangePwd(@RequestBody Map<String, Object> params,HttpServletRequest request, HttpServletResponse response,Model model) throws Exception {
    	Map<String,Object> mapres = new HashMap<String,Object>();
    	if(params.get("newPassword")==null || "".equals(params.get("newPassword").toString())){
    		mapres.put("errorCode", "10002");
    		mapres.put("errorMessage", "重置密码不能为空");
    		return mapres;
    	}
    	String managerId = request.getSession().getAttribute("s_user_id").toString();
    	String password = params.get("newPassword").toString();
        Map<String, Object> mapm = new HashMap<String, Object>();
        mapm.put("id", managerId);
        mapm.put("password", MD5Util.GetMD5Code(password));
        int effectRow = personService.changePwd(mapm);
        if(effectRow<=0){
        	mapres.put("errorCode", "10003");
     		mapres.put("errorMessage", "密码重置失败，请重新重置。");
            return mapres;
        }
        mapres.put("errorCode", "0");
		mapres.put("successMsg", "密码重置成功");
        return mapres;
    }

    public String getRandomNum(){
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String mhtOrderStartTime = dateFormat.format(new Date());
        Random random = new Random();
        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
        return mhtOrderStartTime+rannum;// 当前时间
    }
}
